package com.dc.project.controller.user;

import com.dc.project.util.TaskSseEmitterUtil;
import com.own.aop.login.LoginIgnore;
import com.own.aop.operation.LogOperationModuleAop;
import com.own.constant.ConstantBeanSuffix;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

/**
 * UserClientSseController
 *
 * @author chenxueli
 * @date 2025-03-12 09:09:00
 */
@Slf4j
@Tag(name = "SSE" + ConstantBeanSuffix.CONTROLLER)
@RestController
@LoginIgnore
@CrossOrigin("*")
@LogOperationModuleAop("SSE")
@RequestMapping("sse")
public class UserClientSseController {

    @Resource
    private TaskSseEmitterUtil taskSseEmitterUtil;

    @Operation(summary = "链接sse（taskId）")
    @GetMapping("/connect/task/{taskId}")
    public SseEmitter connect(
            @Parameter(description = "任务id", required = true) @PathVariable Long taskId
    ) {
        var emitter = new SseEmitter(Long.MAX_VALUE);
        taskSseEmitterUtil.put(taskId, emitter);
        try {
            // 发送初始连接成功消息
            emitter.send(SseEmitter.event().name("CONNECT").data("连接成功"));
        } catch (Exception ex) {
            emitter.completeWithError(ex);
        }
        return emitter;
    }

}
